package main

import (
	"fmt"
	"github.com/go-redis/redis/v8"
)

func main() {
	// 创建 Redis 客户端
	client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379", // Redis 服务器地址
		Password: "",               // Redis 密码
		DB:       2,                // Redis 数据库索引
	})

	// 创建 Lua 脚本
	scriptMax := `
		local key = KEYS[1]
		local score = tonumber(ARGV[1])
		local member = ARGV[2]
		local currentScore = tonumber(redis.call('ZSCORE', key, member))
		if currentScore == nil or score > currentScore then
			redis.call('ZADD', key, score, member)
			return score
		end
		return currentScore
	`
	sha, err := Scrip(*client, scriptMax)
	if err != nil {
		return
	}
	result, err := EvalSha(*client, sha, []string{"myzset:Key"}, 34, "TestValue")
	if err != nil {
		return
	}
	// 输出结果
	fmt.Println("Sorted set size:", result)
}

/*func Scrip(client redis.Client, key string, score float64, member interface{}) (int64, error) {
	v, err := client.ScriptLoad(client.ctx, key, &redis.Z{Score: score, Member: member}).Result()
	if err != nil {
		if err != Nil {
			fmt.Printf("redis ZAdd key(%v) err: %s", key, err)
		}
		return v, err
	}
	return v, nil
}*/
func Scrip(client redis.Client, scrip string) (string, error) {
	v, err := client.ScriptLoad(client.Context(), scrip).Result()
	if err != nil {
		if err != nil {
			fmt.Printf("redis scrip(%v) err: %s", scrip, err)
		}
		return v, err
	}
	return v, nil
}
func EvalSha(client redis.Client, sha1 string, keys []string, args ...interface{}) (interface{}, error) {
	v, err := client.EvalSha(client.Context(), sha1, keys, args).Result()
	if err != nil {
		if err != nil {
			fmt.Printf("redis scrip(%v) err: %s", sha1, err)
		}
		return v, err
	}
	return v, nil
}
